package com.hqyj.javaSpringBoot.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class ControllerAspect {

    private final static  Logger LOGGER= LoggerFactory.getLogger(ControllerAspect.class);

    /**
     * @Pointcut在所有控制层的方法上插入切点
     * @Order(1)    数字越低级别越高
     */
    @Pointcut("execution(public * com.hqyj.javaSpringBoot.modules.*.controller.*.*(..))")
    @Order(1)
    public void controllerPointCut(){};

    /**自定义注释，作用在方法上*/
    @Pointcut("@annotation(com.hqyj.javaSpringBoot.aspect.MyAnnotation)")
    @Order(1)
    public void myAnnotation(){};

    @Before(value = "controllerPointCut()")
    public void beforeController(JoinPoint joinPoint){
        LOGGER.debug("=====before controller");

        ServletRequestAttributes servletRequestAttributes=
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=servletRequestAttributes.getRequest();
        LOGGER.debug(String.format("aop切面请求 请求来源：：%s",request.getRemoteAddr()));
        LOGGER.debug(String.format("请求URL：：%s",request.getRequestURL()));
        LOGGER.debug(String.format("请求方式：：%s",request.getMethod()));
        LOGGER.debug(String.format("请求类：：%s",joinPoint.getTarget().getClass().getName()));
        LOGGER.debug(String.format("请求方法：：%s",joinPoint.getSignature()));
        LOGGER.debug("请求参数："+joinPoint.getArgs());
    }

    @Around(value = "controllerPointCut()")
    public Object aroundController(ProceedingJoinPoint proceedingJoinPoint)
            throws Throwable {
        LOGGER.debug("=====around controller");
        return proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    }

    @After(value = "controllerPointCut()")
    public void afterController(){
        LOGGER.debug("=====after controller");

    }

    @Around(value = "myAnnotation()")
    public Object aroundMyannotation(ProceedingJoinPoint proceedingJoinPoint)
            throws Throwable {
        LOGGER.debug("===========around myAnnotation");

        long start=System.currentTimeMillis();
        Object result=proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        long end=System.currentTimeMillis();
        LOGGER.debug(String.format("执行时间为：%s",end-start));
        return result;
    }
}
